package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 购物车
 */
@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加菜品或套餐到购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        log.info("购物车数据：{}", shoppingCart);

        //设置用户id执行当前是哪个用户是购物车数据
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        Long dishId = shoppingCart.getDishId();

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, currentId);

        if (dishId != null) {
            //添加到购物车的是菜品
            queryWrapper.eq(ShoppingCart::getDishId, dishId);
        } else {
            //添加到购物车的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }

        //查询当前菜品或套餐是否在购物车中
        ShoppingCart shoppingCartOne = shoppingCartService.getOne(queryWrapper);

        if (shoppingCartOne != null) {
            //如果已经存在，就在原来数据的基础上加一:number+1
            Integer number = shoppingCartOne.getNumber();
            shoppingCartOne.setNumber(number + 1);
            shoppingCartService.updateById(shoppingCartOne);
        } else {
            //如果不存在，则添加到购物车，数量设置一下默认就是一（因为前端传递过来的数据number没有值）
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            //为了响应结果方便，就把shoppingCart赋值给shoppingCartOne同一个对象
            shoppingCartOne = shoppingCart;
        }
        return R.success(shoppingCartOne);

    }

    /**
     * 查看购物车
     *
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        log.info("查看购物车...");

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByAsc(ShoppingCart::getCreateTime);
        //根据用户id查询用户的购物车信息 select * from shopping_cart where user_id=?
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        LambdaQueryWrapper<ShoppingCart> queryWrapper1 = new LambdaQueryWrapper<>();
        //购物车中菜品或套餐的分数number为0的时候就从购物车中删除
       list=list.stream().map((item)->{
           Integer number = item.getNumber();
            Long shoppingCartId = item.getId();
           Long dishId = item.getDishId();
           Long setmealId = item.getSetmealId();
           if(number==0){
               queryWrapper1.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
                if (dishId!=null){
                    //减一操作的是菜品
                    queryWrapper.eq(ShoppingCart::getDishId,dishId);
                }else {
                    //减一操作的是套餐
                    queryWrapper.eq(ShoppingCart::getSetmealId,setmealId);
                }
               shoppingCartService.remove(queryWrapper);
           }
           return item;
       }).collect(Collectors.toList());
        return R.success(list);
    }


    @DeleteMapping("/clean")
    public R<String> clean(){
        log.info("清空购物车...");
        shoppingCartService.clean();
        return R.success("购物车清空成功");
    }

    /**
     * 购物车中已经存在的菜品或者套餐减一操作
     * @return
     */
    @PostMapping("/sub")
    public R<ShoppingCart> subOne(@RequestBody Map map){
        log.info("map:{}",map);
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        //获取菜品的id
        String dishId=null;
        if (map.get("dishId")!=null){
           dishId = map.get("dishId").toString();
        }
        if (dishId!=null){
            //减一操作的是菜品
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
        }else {
            //减一操作的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId,map.get("setmealId"));
        }
        //执行更新number操作
        ShoppingCart shoppingCartOne = shoppingCartService.getOne(queryWrapper);
        Integer number=0;
        if (shoppingCartOne!=null){
            //加一个非空判断，解决空指针异常
            number = shoppingCartOne.getNumber();
        }
        if (number<1){
            return R.error("该商品个数已经为零");
        }
        shoppingCartOne.setNumber(number-1);

        shoppingCartService.updateById(shoppingCartOne);
        return R.success(shoppingCartOne);
    }
}
